package cn.xiaolang.event.spring;

import lombok.extern.slf4j.Slf4j;
import org.greenrobot.eventbus.EventBus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * @author Dean
 * @date 2021-05-18
 * @link { https://github.com/greenrobot/EventBus }
 */
@Slf4j
@Component
public class DnEventBusContext {

    private final EventBus eventBus;

    private final DnEventListener eventListener;

    @Autowired
    public DnEventBusContext(EventBus eventBus, DnEventListener eventListener) {
        this.eventBus = eventBus;
        this.eventListener = eventListener;
    }

    @PostConstruct
    public void init() {
        eventBus.register(eventListener);
    }

    @PreDestroy
    public void destroy() {
        eventBus.unregister(eventListener);
    }

    public void eventPost(Object event) {
        eventBus.post(event);
        log.info("post:{}", event);
    }
}